package com.atguigu.yygh.msm.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.hosp.globalexp.YyghException;
import com.atguigu.yygh.hosp.util.HttpUtils;
import com.atguigu.yygh.msm.service.MsmService;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public void sendCode(String phone) {
//1.先检查Redis里面是否存在有效的验证码,如果有有效的验证码直接返回不再发送短信
        String codeFromRedis = stringRedisTemplate.boundValueOps(phone).get();
        if(!StringUtils.isEmpty(codeFromRedis)){
            return;
        }

//2.调用第三方短信接口
        String host = "https://wwsms.market.alicloudapi.com";//第三方接口的域名
        String path = "/send_sms";    //路径
        String method = "POST";       //请求方式

//3.改成自己的appcode
        String appcode = "84bccdc0578641fd90d4a1a16f9768ff";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();

//4.生成4位随机数验证码
        //Math.random()是随机的小数*10000,变成整数位有4位,加上long强转,只保留整数位
        long code = (long) (Math.random() * 10000);
        if(code<1000){
            code+=1000;
        }
        bodys.put("content", "code:"+code);
        bodys.put("template_id", "TPL_0000");
        bodys.put("phone_number", phone);

//5.使用HttpUtil工具类发起post类型的请求.调用第三方短信接口
        HttpResponse response = null;
        try {
            response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));

            /**
             * 如何判断短信发送成功  200+ok
             */
           /* StatusLine statusLine = response.getStatusLine(); //获取响应状态行
            int statusCode = statusLine.getStatusCode();       //获取响应状态码*/

            /**
             * response.getEntity() 获取响应的实体部分，即HTTP响应的主体内容。
             * EntityUtils.toString(response.getEntity()) 将响应实体转换为字符串表示。
             * 这个方法会自动处理字符编码，并将实体内容转换为对应的字符串。
             */
//6.第三方短信接口的返回值
        String responseString = null;
        try {
            responseString = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Map map = JSON.parseObject(responseString, Map.class);
            Object status = map.get("status");
            if(!StringUtils.isEmpty(status)&& "ok".equalsIgnoreCase(String.valueOf(status))){
                stringRedisTemplate.boundValueOps(phone).set(String.valueOf(code),5, TimeUnit.MINUTES);
            }else {
                //该异常希望被全局异常处理器去捕获(不能放在try-catch里)
                throw new YyghException(20001,"验证码发送失败,"+responseString);
            }
    }
}
